package exercise;

import java.util.ArrayList;
import java.util.List;

public class LC54 {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> ans = new ArrayList<>();

        int m = matrix.length, n = matrix[0].length, maxSz = m * n;
        int i = 0, j = 0;
        while (ans.size() < maxSz) {
            while (ans.size() < maxSz && j <= n - 1) {
                if (matrix[i][j] == Integer.MAX_VALUE) break;
                ans.add(matrix[i][j]);
                matrix[i][j] = Integer.MAX_VALUE;
                j++;
            }
            j--; i++;
            while (ans.size() < maxSz && i <= m - 1) {
                if (matrix[i][j] == Integer.MAX_VALUE) break;
                ans.add(matrix[i][j]);
                matrix[i][j] = Integer.MAX_VALUE;
                i++;
            }
            i--; j--;
            while (ans.size() < maxSz && j >= 0) {
                if (matrix[i][j] == Integer.MAX_VALUE) break;
                ans.add(matrix[i][j]);
                matrix[i][j] = Integer.MAX_VALUE;
                j--;
            }
            j++; i--;
            while (ans.size() < maxSz && i >= 0) {
                if (matrix[i][j] == Integer.MAX_VALUE) break;
                ans.add(matrix[i][j]);
                matrix[i][j] = Integer.MAX_VALUE;
                i--;
            }
            i++; j++;
        }
        return ans;
    }
}
